/**
 * Created by lghdb on 2018/7/9.
 * 程序入口
 */
const Koa = require('koa');
const router = require('koa-router')();
var bodyParser = require('koa-bodyparser');
var program = require('commander');
const session = require('koa-session');
const controller = require('./controller');
var template = require('./templating')
var config = require('./config');

const app = new Koa();
app.keys = ['some secret hurr'];
/**
 * 处理命令行参数
 */
program
    .version("2.0.0", '-v, --version')
    .option("-f, --config [value]", "Config file default 'config/docker-reg-config.json'")
    .option("-e, --env [value]", "Run env default 'dev'")
    .parse(process.argv);

var configDir = program.config || "config/docker-reg-web.json";
var env = program.env ||  process.env.NODE_ENV || "dev";
/**
 * 加载配置
 */
console.log(`Running dev is '${env}', Config file path is '${configDir}'`);
const isProduction = env === 'pro';
config.load(configDir, env);
console.log(global.appConfig);


/**
 * 设置app
 */
app.keys = config.get("keys");
const CONFIG = {
    key: 'koa:sess',
    maxAge: 1800000,
    overwrite: true,
    httpOnly: true,
    signed: true,
    rolling: false,
    renew: false,
};
app.use(session(CONFIG, app));

app.use(async (ctx, next) => {
    if (ctx.path === '/favicon.ico') return;
    console.log(`Process ${ctx.request.method} ${ctx.request.url} `);
    var start = new Date().getTime(),
        execTime;
    await next();

    execTime = new Date().getTime() - start;
    ctx.response.set('X-Response-Time', `${execTime}ms`);
});

app.use(require('./staticFiles')('/assets/', __dirname + '/assets'));

app.use(bodyParser());

app.use(template('views', {
    noCache: !isProduction,
    watch: !isProduction
}));

//登录检查
app.use(require('./login_require'));

app.use(controller());

var server = app.listen(config.get('port'), function () {
    var host = server.address().address;
    var port = server.address().port;
    if (host == "::"){
        host = "localhost"
    }
    console.log('docker-reg-web app listening at http://%s:%s', host, port);
});